import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';

import { Spin, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

import LinkButton from '../LinkButton';

import memory from '../../utils/memoryUtils';
import storage from '../../utils/storageUtils';
import { reqWeather } from '../../api';
import menuList from '../../config/menuConfig';
import Time from './Time';

import theme from '../../config/theme';

import './index.less';

/**
 * 头部组件
*/
function Header(props) {
    const [weather, setWeather] = useState(<Spin size="small" />);
    const { pathname } = props.location;
    const { history } = props;

    useEffect(() => {
        getWeather(setWeather);
    }, [])

    const { user } = memory;
    return (
        <div className="right-header">
            <div className="right-header-top" style={{ 'borderBottom': '1px solid ' + theme['@primary-color'] }}>
                <LinkButton onClick={() => confirm(history)}>退出</LinkButton>
                <span>欢迎，{user.username}</span>
            </div>
            <div className="right-header-bottom">
                <div className="right-header-bottom-left">
                    {getTitle(menuList, pathname)}
                </div>
                <div className="right-header-bottom-right">
                    <Time />
                    <span className="weather">{weather}</span>
                </div>
            </div>
        </div>
    )
}

async function getWeather(setWeather) {
    const res = await reqWeather();

    if (res.status === 0) {
        const { now } = res.result;
        setWeather(`${now.text} ${now.temp}℃ ${now.wind_dir}${now.wind_class}`);
    }
}

function getTitle(list, path) {
    let title = '';
    if (path && path.startsWith('/product')) {
        return '商品管理';
    }

    list.some(item => {
        if (item.key === path) {
            title = item.title;
            return true;
        } else if (item.children && item.children.length !== 0) {
            title = getTitle(item.children, path);
            return title ? true : false;
        }
        return false;
    });
    return title;
}

function confirm(history) {
    Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '确认退出当前用户吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
            memory.user = null;
            storage.delUser();
            history.replace('/login');
        }
    });

}

export default withRouter(Header);